<template>
  <div>
    <el-dialog
      v-loading="loading"
      class="mt-dialog"
      :title="domain + title + currentOpRow.local_id"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      top="80px"
      width="1280px"
      @close="close"
    >
      <el-input
        v-if="local_id !==''"
        v-model="local_id"
        placeholder="请输爬取产品ID"
        class="input-with-select"
        clearable
        :disabled="getloading"
      >
        <el-button slot="append" icon="el-icon-search" :loading="getloading" :disabled="loading" @click="handleSearch">
          拉取产品信息
        </el-button>
      </el-input>
      <div :style="showinfo">
        <el-tabs v-model="activeName" @tab-click="handleModifyTabClick">
          <el-tab-pane label="基本信息" name="first">
            <el-form ref="currentOpRow" :model="currentOpRow" label-width="100px">
              <el-form-item label="标题">
                <el-input v-model="currentOpRow.name" placeholder="产品标题" @change="modified=true">
                  <el-button slot="append" :loading="ailoading" @click="handleAIRewriteTitle(currentOpRow)">AI重写</el-button>
                  <!--                  <el-dropdown  slot="append" :loading="ailoading" split-button type="primary" @click="handleAIRewriteTitle(currentOpRow)">-->
                  <!--                    AI重写-->
                  <!--                    <el-dropdown-menu slot="dropdown">-->
                  <!--                      <el-dropdown-item  @click="handleAIRewritePromote(currentOpRow)">写促销信息</el-dropdown-item>-->
                  <!--                    </el-dropdown-menu>-->
                  <!--                  </el-dropdown>-->
                  <el-button slot="append" type="primary" size="mini" :loading="aipromote_loading" @click="handleAIRewritePromote(currentOpRow)">写描述</el-button>
                </el-input>
                <span v-if="currentOpRow.name_old">原标题:{{ currentOpRow.name_old }}</span>

              </el-form-item>
              <el-form-item label="长描述">
                <tinymce ref="mteditdlongdescription" v-model="currentOpRow.long_description" :height="450" @input="handleChangeDescription" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <!--          <el-tab-pane label="长描述" name="second2">-->
          <!--            <el-form ref="currentOpRow" :model="currentOpRow" label-width="80px">-->

          <!--            </el-form>-->
          <!--          </el-tab-pane>-->
          <el-tab-pane label="图片信息" name="first2">
            <el-table ref="imageTable" :data="currentOpRow.image_list" style="width: 100%" height="500" @selection-change="handleChangeImagelist">
              <el-table-column
                type="selection"
                width="55"
              />
              <el-table-column align="center" label="图片" prop="url" sortable="custom">
                <template slot-scope="scope">
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="scope.row.url"
                    :title="scope.row.url"
                    :preview-src-list="[scope.row.url]"
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" label="主图" prop="main" sortable="custom">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.main"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    @change="handleStatusChange(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column align="center" label="修改链接" prop="main" sortable="custom">
                <template slot-scope="scope">

                  <el-button type="text" size="mini" @click="handleModifyImageUrl(scope.row)">替换图片</el-button>
                  <el-button v-if="scope.row.url.indexOf('cloudfront.net') === -1" type="primary" size="mini" @click="handleSaveImageToS3(scope.row.url, currentOpRow.local_id)">CDN保存</el-button>
                  <el-button v-else type="text" size="mini" @click="handleRestoreImage(scope.row.url, currentOpRow.local_id)">还原</el-button>
                  <el-button v-if="!scope.row.waiting_remove_bg" type="success" size="mini" @click="handleShowAddRemoveBg(currentOpRow.local_id, scope.row.url)">
                    去水印
                  </el-button>
                  <el-button v-else type="warning" title="已经添加等待处理" size="mini" disabled @click="handleShowAddRemoveBg(currentOpRow.local_id, scope.row.url)">
                    已添加
                  </el-button>
                  <el-button type="danger" size="mini" @click="handleRemoveImage(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button v-if="remove_bg_urls.length" style="float: left" size="mini" type="danger" @click="handleSaveImageToS3List()">批量CDN
            </el-button>
            <el-button v-if="remove_bg_urls.length" style="float: left" size="mini" type="danger" @click="handleMultiRemoveBgImageList()">批量去水印
            </el-button>
            <el-button style="float: right" size="mini" type="text" @click="handleAddImage(currentOpRow)">增加图片
            </el-button>
          </el-tab-pane>
          <el-tab-pane label="变体&价格" name="second4">
            <el-form ref="currentOpRow" :model="currentOpRow" label-position="top" label-width="120px">
              <el-form-item label="基本价格">
                <el-input v-model="currentOpRow.price" />
                上传产品时自动提高价格?
                <el-switch
                  v-model="currentOpRow.change_price"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                />
                <el-alert
                  v-if="!currentOpRow.change_price"
                  title="注意,当前设置为不自动提价，产品上传时候不会修改价格！"
                  type="error"
                  effect="dark"
                />
              </el-form-item>
              <el-form-item label="本地变体价格">
                <el-button size="mini" type="success" @click="handleReBuildAttrsPrice">重新生成组合</el-button>
                <el-table :data="currentOpRow.attrs_price" style="width: 100%" height="300">
                  <el-table-column align="center" label="属性组合" prop="skunames" sortable="custom" />
                  <el-table-column
                    align="center"
                    label="价格"
                    prop="skuVal.actSkuMultiCurrencyCalPrice"
                    sortable="custom"
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.skuVal.actSkuMultiCurrencyCalPrice"
                        size="mini"
                        class="mt-input-price"
                        @change="handleModifyPrice(scope.row.skuVal)"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="库存" prop="skuVal.availQuantity" sortable="custom" />
                  <el-table-column align="center" label="操作" sortable="custom">
                    <template slot-scope="scope">
                      <el-button size="mini" type="danger" icon="icon-delete" @click="handleSaveAsNewProduct">保存为新产品
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleModifyPriceAll(currentOpRow.attrs_price)">批量修改价格</el-button>
                <el-tag>请注意!本地产品的属性价格为产品实际价格!</el-tag>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="属性" name="second5">
            <el-form ref="currentOpRow" :model="currentOpRow" label-position="left" label-width="120px">
              <el-form-item v-for="item in currentOpRow.attributes" :key="item.name.sku">
                <el-tag>{{ item.name.value }} sku:{{ item.name.sku }}</el-tag>
                <el-button size="mini" type="text" style="color: red" @click="handleModifyAttributeName(item.name)">修改
                </el-button>
                <el-button size="mini" type="text" style="color: green" @click="handleAddAttributeItem(item)">新增item
                </el-button>
                <el-button type="success" size="mini" @click="handleSaveAttributesAsNewProduct(item.name.value)">批量保存为单SKU</el-button>
                <el-table :data="item.values" style="width: 100%" height="500" @selection-change="handleChangeAttributeimages">
                  <el-table-column
                    type="selection"
                    width="55"
                  />
                  <el-table-column align="center" label="名称" prop="value" sortable="custom" />
                  <el-table-column align="center" label="core-sku" prop="core-sku" sortable="custom" />
                  <el-table-column align="center" label="图片" prop="src" sortable="custom">
                    <template slot-scope="scope">
                      <el-image
                        v-if="scope.row.src"
                        style="width: 100px; height: 100px"
                        :title="scope.row.src"
                        :src="scope.row.src"
                        :preview-src-list="[scope.row.src]"
                      />
                      <span v-else />
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="操作" sortable="custom">
                    <template slot-scope="scope">
                      <el-button type="danger" size="mini" @click="handleDeleteAttributeName(item, scope.row)">删除
                      </el-button>
                      <el-button type="warning" size="mini" @click="handleDeleteAttributeNameAllOther(item, scope.row)">
                        删除其他
                      </el-button>
                      <el-button v-if="!scope.row.waiting_remove_bg" type="success" size="mini" @click="handleShowAddRemoveBg(currentOpRow.local_id, scope.row.src)">
                        去水印
                      </el-button>
                      <el-button v-else type="warning" title="已经添加等待处理" size="mini" disabled @click="handleShowAddRemoveBg(currentOpRow.local_id, scope.row.src)">
                        已添加
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-form>
            <el-button v-if="remove_bg_urls.length" style="float: left" size="mini" type="danger" @click="handleMultiRemoveBgImageList()">批量去水印
            </el-button>
            <el-button type="success" style="float: right" size="mini" @click="handleAddNewAttrubuteGroup">增加新属性</el-button>
          </el-tab-pane>
          <el-tab-pane label="meta信息" name="second">
            <el-form ref="currentOpRow" :model="currentOpRow" label-width="240px">
              <el-form-item label="search keyword[custom_label_2]">
                <el-input v-model="currentOpRow.search_keyword" />
              </el-form-item>
              <el-form-item label="meta title">
                <el-input v-model="currentOpRow.meta_title" />
              </el-form-item>

              <el-form-item label="meta description">
                <el-input v-model="currentOpRow.meta_description" type="textarea" />
              </el-form-item>

              <el-form-item label="meta keywords">
                <el-input v-model="currentOpRow.meta_keywords" type="textarea" />
              </el-form-item>
              <el-form-item label="disable">
                <el-switch v-model="currentOpRow.isDisable" />
              </el-form-item>
              <el-form-item label="短描述">
                <tinymce ref="mteditdescription" v-model="currentOpRow.description" :height="300" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
      <span slot="footer" class="dialog-footer" :style="showinfo">
        <el-select slot="prepend" v-model="selected_website" placeholder="选择上传网站" filterable clearable>
          <el-option
            v-for="item in websites"
            :key="item.id"
            :label="item.domain + '|'+ item.tag"
            :value="item.id"
          />
        </el-select>
        <el-switch
          v-model="modify_finsihed"
          active-color="#13ce66"
          inactive-color="#ff4949"
        />
        <el-button type="success" @click="handleSaveAsNewProduct">保存为新产品</el-button>
        <el-button
          v-if="modified"
          type="danger"
          @click="handleSaveModifyLocal"
        >提交修改</el-button>
        <el-button v-else type="primary" @click="handleSaveModifyLocal">修改</el-button>
        <a target="_blank" :href="currentOpRow.url" style="float: left;margin-left: 5px;padding: 5px 5px 5px;">采购</a>
        <el-button :type="modify_saved ? 'success' : ''" style="float: left;margin-left: 5px;padding: 5px 5px 5px;" @click="handleRemoveAllImageBg">一键去水印</el-button>
      </span>
    </el-dialog>
    <el-dialog title="添加图片" :visible.sync="addImageDialogVisible" append-to-body>
      <el-form :model="newImage">
        <el-form-item label="图片链接" :label-width="120">
          <el-input v-model="newImage.url" autocomplete="off" />
        </el-form-item>
        <el-form-item label="主图" :label-width="120">
          <el-switch v-model="newImage.main" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addImageDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddNewImage">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="添加属性值"
      :visible.sync="AddAttributeVisible"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form :model="newAttribute">
        <el-form-item label="名称">
          <el-input v-model="newAttribute.value" autocomplete="off" />
        </el-form-item>
        <el-form-item label="sku">
          <el-input v-model="newAttribute.sku" placeholder="sku必须不同" autocomplete="off" />
        </el-form-item>
        <el-form-item label="属性图片">
          <el-input v-model="newAttribute.src" autocomplete="off" />
        </el-form-item>

        <el-form-item label="增加价格">
          <el-input v-model="newAttribute.extra_price" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="AddAttributeVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddAttribute">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改价格" :visible.sync="dialogModifyPriceVisible">
      <el-form :model="modifyprice_form">
        <el-form-item label="类型" label-width="120px">
          <el-switch
            v-model="modifyprice_form.same_price"
            active-text="同样价格"
            inactive-text="比例"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item label="价格" label-width="120px">
          <el-input v-if="modifyprice_form.same_price" v-model="modifyprice_form.price" type="number" />
          <el-input v-model="modifyprice_form.price" placeholder="输入百分比">
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogModifyPriceVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleChangePrice">确 定</el-button>
      </div>
    </el-dialog>
    <!--     <el-dialog title="去水印" :visible.sync="removeBgVisible" append-to-body-->
    <!--               :close-on-click-modal="false">-->
    <!--      <el-form :model="removeBgForm">-->
    <!--        <el-form-item label="url" v-if="removeBgForm.url !== ''">-->
    <!--           <el-image-->
    <!--              style="width: 100px; height: 100px"-->
    <!--              :src="removeBgForm.url"-->
    <!--              :preview-src-list="[removeBgForm.url]">-->
    <!--            </el-image>-->
    <!--          <el-input v-model="removeBgForm.url" ></el-input>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="urls" v-if="remove_bg_urls.length">-->
    <!--           <el-image-->
    <!--              style="width: 100px; height: 100px"-->
    <!--               v-for="item in remove_bg_urls"-->
    <!--              fit="fill"-->
    <!--              :key="item"-->
    <!--              :src="item"-->
    <!--              :preview-src-list="[item]">-->
    <!--            </el-image>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="产品ID">-->
    <!--          <el-input v-model="remove_bg_product_id" autocomplete="off"></el-input>-->
    <!--        </el-form-item>-->
    <!--         <el-form-item label="服务商">-->
    <!--            <el-select v-model="removeBgForm.service" placeholder=服务商 size="small" filterable clearable>-->
    <!--            <el-option v-for="item in removebgServices" :key="item.value" :label="item.value"-->
    <!--                       :value="item.value"></el-option>-->
    <!--          </el-select>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="图片格式">-->
    <!--          <el-select v-model="removeBgForm.format" placeholder=图片格式 size="small" filterable clearable>-->
    <!--            <el-option value="jpg" label="jpg"></el-option>-->
    <!--            <el-option value="png" label="png"></el-option>-->
    <!--          </el-select>-->
    <!--        </el-form-item>-->
    <!--         <el-form-item label="背景色">-->
    <!--           <el-color-picker v-model="removeBgForm.bg_color"></el-color-picker>-->
    <!--         </el-form-item>-->
    <!--      </el-form>-->
    <!--      <div slot="footer" class="dialog-footer">-->
    <!--        <el-button @click="removeBgVisible = false;removeBgProcessing=false;">取 消</el-button>-->
    <!--        <el-button type="primary" @click="handleAddRemoveBg" :loading="removeBgProcessing">确 定</el-button>-->
    <!--      </div>-->
    <!--    </el-dialog>-->
    <remove-bg
      :is-visible="removeBgVisible"
      :url="remove_bg_url"
      :urls="remove_bg_urls"
      :product_id="remove_bg_product_id"
      :sync="remove_bg_sync"
      @close="removeBgVisible=false"
      @success="removeBgSuccess"
    />
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import {
  crawl_modify_local, crawl_update_directly_upload_remote, crawl_save_as_new
} from '@/api/erp/crawlproduct'

import {
  Post as OpenAiPost
} from '@/api/cms/openai'

import {
  GetPsProduct,
  FixAttributes,
  DeleteAttribute,
  ModifyPsProductWeight,
  GetPsProductWeight
} from '@/api/prestashop/prestashopapi'
import RemoveBg from './remove-bg'
import { SaveImageToS3, Get as GetRemovedImage } from '../../../api/erp/removebgimages'
import qs from 'qs'
// import Feedproduct from "@/views/orders/element/feedproduct"
// import modifymultiprice from "@/views/prestashop/element/modifymultiprice"
// import orderdetail from '@/views/orders/element/orderdetail'

function descartes(value_list) {
  if (value_list.length < 2) return value_list[0] || []

  return [].reduce.call(value_list, function(col, set) {
    var res = []
    col.forEach(function(c) {
      set.forEach(function(s) {
        var t = [].concat(Array.isArray(c) ? c : [c])
        t.push(s)
        res.push(t)
      })
    })
    return res
  })
}

export default {
  name: 'Prestaproduct',
  components: { RemoveBg, Tinymce },
  props: ['pstVisible', 'domain', 'product_id', 'local_id'],
  data() {
    return {
      modify_finsihed: true,
      modify_saved: false,
      modified: false,
      dialogModifyPriceVisible: false,
      modifyprice_form: {
        same_price: false,
        price: 0
      },
      removeBgVisible: false,
      remove_bg_url: '',
      remove_bg_urls: [],
      remove_bg_product_id: '',
      remove_bg_sync: false, // 是否立即返回
      removeBgProcessing: false,
      removeBgForm: {
        url: '',
        urls: [],
        product_id: '',
        service: 'picwish',
        bg_color: '#ffffff',
        format: 'jpg'
      },
      removebgServices: [
        { value: 'picwish' },
        { value: 'remove.bg' }
      ],
      websites: [],
      selected_website: '',
      modify_weight: 0,
      modify_weight_loading: false,
      orderdetailVisual: false,
      multiModifyPriceShown: false,
      feedproductVisual: false,
      title: '修改产品',
      activeName: 'first',
      getloading: false,
      dialogVisible: false,
      loading: false,
      url: '',
      ailoading: false,
      aipromote_loading: false,
      ps_product_id: '',
      showinfo: 'display:none;',
      searchResults: [],
      searchImageUrl: '',
      upload_task_id: '',
      update_direct_remote_loading: false,
      temp_all_price: 0,
      useModifyPrice: 0,
      clean_cache_url: '',
      original_name: '',
      currentOpRow: {
        'id': 0,
        'modify_finsihed': true,
        'change_price': true,
        'attributes': {},
        'same_price': true,
        'name': '',
        'price': '',
        'description': '',
        'long_description': '',
        'meta_title': '',
        'meta_description': '',
        'meta_keywords': '',
        'image_list': [],
        'upload_tasks': [],
        'fix_ps_attributes': [],
        'attrs_price': []
      },
      addImageDialogVisible: false,
      newImage: {
        url: '',
        id_image: '',
        main: false
      },
      newAttribute: {
        'value': '',
        'src': '',
        'sku': '',
        'core-sku': '',
        'extra_price': 0
      },
      currentAttribute: {},
      AddAttributeVisible: false
    }
  },
  watch: {
    product_id(v) {
      if (v) {
        this.ps_product_id = v
      }
    },
    local_id(v) {
      this.title = this.local_id !== '' ? '爬取到本地产品修改' : '远程网站产品修改'
    },
    pstVisible(v) {
      this.dialogVisible = v
      if (v) {
        this.activeName = 'first'
        this.handleSearch()
      }
    }
  },
  methods: {
    handleReBuildAttrsPrice() {
      const values_list = []
      console.log('attributes:', this.currentOpRow.attributes)
      // 属性分组
      this.currentOpRow.attributes.forEach(item => {
        if (item['values'].length > 0) {
          // 注意这里是数组中的数组
          values_list.push(item['values'])
        }
      })
      const new_array = descartes(values_list)
      console.log(values_list, new_array)
      var attrs_price = []
      for (let i = 0; i < new_array.length; i++) {
        var actSkuCalPrice = parseFloat(this.currentOpRow.price)
        var item = {
          'skuPropIds': [],
          'skunames': []
        }
        console.log(actSkuCalPrice, new_array[i])
        // 多个属性有乘积
        if (new_array[i].length !== undefined) {
          for (let j = 0; j < new_array[i].length; j++) {
            console.log('new array:', j, new_array[i][j])
            item['skuPropIds'].push(new_array[i][j]['core-sku'])
            item['skunames'].push(new_array[i][j]['value'])
            if ('extra_price' in new_array[i][j]) {
              console.log('add extra price')
              actSkuCalPrice += parseFloat(new_array[i][j]['extra_price'])
            }
          }
        } else {
          // 单一属性没有乘积
          item['skuPropIds'].push(new_array[i]['core-sku'])
          item['skunames'].push(new_array[i]['value'])
          if ('extra_price' in new_array[i]) {
            console.log('add extra price')
            actSkuCalPrice += parseFloat(new_array[i]['extra_price'])
          }
        }

        item['skuVal'] = {
          'actSkuBulkCalPrice': String(actSkuCalPrice.toFixed(2)),
          'actSkuCalPrice': String(actSkuCalPrice.toFixed(2)),
          'actSkuMultiCurrencyBulkPrice': String(actSkuCalPrice.toFixed(2)),
          'actSkuMultiCurrencyCalPrice': String(actSkuCalPrice.toFixed(2)),
          'actSkuMultiCurrencyDisplayPrice': String(actSkuCalPrice.toFixed(2)),
          'availQuantity': 100000,
          'isActivity': true
        }
        item['skuPropIds'] = item['skuPropIds'].join(',')
        item['skunames'] = item['skunames'].join(',')
        console.log(item)
        attrs_price.push(item)
      }
      this.currentOpRow.attrs_price = attrs_price
    },
    handleAddNewAttrubuteGroup() {
      this.$prompt('请输入新名称', '增加新属性组:', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        this.currentOpRow.attributes.push({
          'name': { 'value': value, 'sku': Math.ceil(Math.random() * 10000000) },
          'values': []
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    isSKUExists(sku) {
      for (let i = 0; i < this.currentOpRow.attributes.length; i++) {
        for (let j = 0; j < this.currentOpRow.attributes[i].values.length; j++) {
          if (this.currentOpRow.attributes[i].values[j]['core-sku'] === String(sku)) {
            return true
          }
        }
      }
      return false
    },
    confirmAddAttribute() {
      if (this.isSKUExists(this.newAttribute.sku) === true) {
        this.$message({
          type: 'error',
          message: 'SKU已经存在'
        })
        return
      }
      this.currentOpRow.attributes.forEach(item => {
        if (item.name.value === this.currentAttribute.name.value) {
          this.newAttribute['core-sku'] = this.newAttribute.sku
          const new_attibute = Object.assign({}, this.newAttribute)
          this.currentAttribute.values.push(new_attibute)
          this.newAttribute = {
            'value': '',
            'src': '',
            'sku': '',
            'core-sku': '',
            'extra_price': 0
          }
          this.$message.success('添加属性成功,自动重新生成组合')
          this.handleReBuildAttrsPrice()
        }
      })
      this.AddAttributeVisible = false
    },
    handleAddAttributeItem(row) {
      this.AddAttributeVisible = true
      this.currentAttribute = row
    },
    handleSaveAttributesAsNewProduct(sku_name) {
      // 把这个产品属性全部保存为新产品
      const data = this.currentOpRow
      data['single_sku_name'] = sku_name
      this.loading = true
      crawl_save_as_new(JSON.stringify({
        data: data
      }))
        .then(response => {
          this.$notify({
            title: '成功',
            message: response.msg,
            type: 'success',
            duration: 2000
          })
          this.loading = false
        }).catch(err => {
          this.$notify({
            title: '失败',
            message: err,
            type: 'success',
            duration: 2000
          })
          this.loading = false
        })
    },
    handleModifyAttributeName(row) {
      this.$prompt('请输入新名称', '原名称:' + row.value, {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        row.value = value
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    confirmAddNewImage() {
      this.currentOpRow.image_list.push(this.newImage)
      this.addImageDialogVisible = false
    },
    handleAddImage(row) {
      this.addImageDialogVisible = true
    },
    resetCurrentRow() {
      this.currentOpRow = {
        'id': 0,
        'same_price': true,
        'change_price': true,
        'name': '',
        'price': '',
        'description': '',
        'long_description': '',
        'long_description_original': '',
        'meta_title': '',
        'meta_description': '',
        'meta_keywords': '',
        'image_list': [],
        'upload_tasks': [],
        'fix_ps_attributes': [],
        'attrs_price': []
      }
    },
    handleGetWeight(row) {
      this.modify_weight_loading = true
      GetPsProductWeight({
        domain: this.domain,
        id_product: this.ps_product_id

      }
      ).then(response => {
        this.modify_weight_loading = false
        this.modify_weight = response.data.weight
      })
    },
    handleModifyWeight(row) {
      this.loading = true
      ModifyPsProductWeight({
        weight: this.modify_weight,
        domain: this.domain,
        id_product: this.ps_product_id

      }
      ).then(response => {
        this.loading = false
        this.$notify({
          title: '成功',
          message: '',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleChangePrice() {
      if (this.modifyprice_form.same_price) {
        this.currentOpRow.attrs_price.forEach(item => {
          this.currentOpRow.price_modify = this.modifyprice_form.price
          item.skuVal.actSkuMultiCurrencyCalPrice = this.modifyprice_form.price
          item.skuVal.actSkuCalPrice = this.modifyprice_form.price
          item.skuVal.skuMultiCurrencyCalPrice = this.modifyprice_form.price
          item.skuVal.skuMultiCurrencyDisplayPrice = this.modifyprice_form.price
          item.skuVal.actSkuMultiCurrencyDisplayPrice = this.modifyprice_form.price
          item.skuVal.skuCalPrice = this.modifyprice_form.price
        })
      } else {
        this.currentOpRow.attrs_price.forEach(item => {
          this.currentOpRow.price_modify = ((this.currentOpRow.price_modify * this.modifyprice_form.price) / 100 | 0) + 0.99
          item.skuVal.actSkuMultiCurrencyCalPrice = ((item.skuVal.actSkuMultiCurrencyCalPrice * this.modifyprice_form.price) / 100 | 0) + 0.99
          item.skuVal.actSkuCalPrice = item.skuVal.actSkuMultiCurrencyCalPrice
          item.skuVal.skuMultiCurrencyCalPrice = item.skuVal.actSkuMultiCurrencyCalPrice
          item.skuVal.skuMultiCurrencyDisplayPrice = item.skuVal.actSkuMultiCurrencyCalPrice
          item.skuVal.actSkuMultiCurrencyDisplayPrice = item.skuVal.actSkuMultiCurrencyCalPrice
          item.skuVal.skuCalPrice = item.skuVal.actSkuMultiCurrencyCalPrice
        })
      }
      this.$message.success('修改完成，提交才会生效')
      this.dialogModifyPriceVisible = false
    },
    handleModifyPriceAll(row) {
      this.dialogModifyPriceVisible = true
      // this.$prompt('请输入价格', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消'
      // }).then(({ value }) => {
      //   row.forEach(item => {
      //     this.currentOpRow.price_modify = value
      //     item.skuVal.actSkuMultiCurrencyCalPrice = value
      //     item.skuVal.actSkuCalPrice = value
      //     item.skuVal.skuMultiCurrencyCalPrice = value
      //     item.skuVal.skuMultiCurrencyDisplayPrice = value
      //     item.skuVal.actSkuMultiCurrencyDisplayPrice = value
      //     item.skuVal.skuCalPrice = value
      //   })
      // }).catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '取消输入'
      //   });
      // });
    },
    handleModifyPriceAllbyPercent(row) {
      this.$prompt('请输入价格比例', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        row.forEach(item => {
          item.skuVal.actSkuMultiCurrencyCalPrice = (value * parseFloat(item.skuVal.actSkuMultiCurrencyCalPrice)).toFixed(2)
          item.skuVal.actSkuCalPrice = (value * parseFloat(item.skuVal.actSkuMultiCurrencyCalPrice)).toFixed(2)
          item.skuVal.skuMultiCurrencyCalPrice = (value * parseFloat(item.skuVal.actSkuMultiCurrencyCalPrice)).toFixed(2)
          item.skuVal.skuMultiCurrencyDisplayPrice = (value * parseFloat(item.skuVal.actSkuMultiCurrencyCalPrice)).toFixed(2)
          item.skuVal.actSkuMultiCurrencyDisplayPrice = (value * parseFloat(item.skuVal.actSkuMultiCurrencyCalPrice)).toFixed(2)
          item.skuVal.skuCalPrice = (value * parseFloat(item.skuVal.actSkuMultiCurrencyCalPrice)).toFixed(2)
        })
        this.currentOpRow.price_modify = (value * parseFloat(this.currentOpRow.price_modify)).toFixed(2)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    handleModifyPrice(row) {
      this.currentOpRow.price_modify = row.actSkuMultiCurrencyCalPrice
      row.actSkuCalPrice = row.actSkuMultiCurrencyCalPrice
      row.skuMultiCurrencyCalPrice = row.actSkuMultiCurrencyCalPrice
      row.skuMultiCurrencyDisplayPrice = row.actSkuMultiCurrencyCalPrice
      row.actSkuMultiCurrencyDisplayPrice = row.actSkuMultiCurrencyCalPrice
      row.skuCalPrice = row.actSkuMultiCurrencyCalPrice
    },
    handleChangeAttributeimages(val) {
      if (val.length) {
        this.remove_bg_urls = val.filter(node => node.src && node.src.length > 0).map(item => { return item.src })
      } else {
        this.remove_bg_urls = []
      }
    },
    handleChangeImagelist(val) {
      if (val) {
        this.remove_bg_urls = val.map(item => { return item.url })
      } else {
        this.remove_bg_urls = []
      }
    },
    handleRestoreImage(url) {
      GetRemovedImage('', qs.stringify({ 'url': url })).then(response => {
        this.$notify({
          title: '查询成功',
          message: '',
          type: 'success',
          duration: 2000
        })
        const val = response.data.data
        if (val.length) {
          for (let i = 0; i < val.length; i++) {
            console.log(val[i])
            this.handleUpdateImageRemoveWating({ 'url': val[i].removed_url, 'removed_url': val[i].url })
          }
        }
      }).catch(err => {
        this.$notify({
          title: '失败',
          message: err,
          type: 'success',
          duration: 2000
        })
      })
    },
    handleSaveImageToS3List() {
      const formdata = {
        urls: this.remove_bg_urls,
        url: '',
        product_id: this.currentOpRow.local_id,
        service: 'only_save'
      }
      SaveImageToS3(formdata).then(response => {
        this.$notify({
          title: '提交成功',
          message: '',
          type: 'success',
          duration: 2000
        })
        const val = response.data.data
        if (val.length) {
          for (let i = 0; i < val.length; i++) {
            console.log(val[i])
            this.handleUpdateImageRemoveWating(val[i])
          }
          this.remove_bg_urls = []
          this.remove_bg_url = ''
          this.remove_bg_product_id = ''
          this.removeBgVisible = false
        }
      }).catch(err => {
        this.$notify({
          title: '失败',
          message: err,
          type: 'success',
          duration: 2000
        })
      })
    },
    handleSaveImageToS3(url, product_id) {
      const formdata = {
        url: url,
        urls: [],
        product_id: product_id || '',
        service: 'only_save'
      }
      SaveImageToS3(formdata).then(response => {
        this.$notify({
          title: '提交成功',
          message: '',
          type: 'success',
          duration: 2000
        })
        const val = response.data.data
        if (val.length) {
          for (let i = 0; i < val.length; i++) {
            console.log(val[i])
            this.handleUpdateImageRemoveWating(val[i])
          }
          this.remove_bg_urls = []
          this.remove_bg_url = ''
          this.remove_bg_product_id = ''
          this.removeBgVisible = false
        }
      }).catch(err => {
        this.$notify({
          title: '失败',
          message: err,
          type: 'success',
          duration: 2000
        })
      })
    },
    removeBgSuccess(val) {
      console.log(val)
      this.$message.success('添加成功，等待队列处理')
      if (val.length) {
        for (let i = 0; i < val.length; i++) {
          console.log(val[i])
          this.handleUpdateImageRemoveWating(val[i])
        }
        this.remove_bg_urls = []
        this.remove_bg_url = ''
        this.remove_bg_product_id = ''
        this.removeBgVisible = false
      } else {
        this.$message.error('去水印失败，没有返回结果')
      }
    },
    handleShowAddRemoveBg(id, url) {
      this.remove_bg_url = url
      this.remove_bg_sync = false
      this.remove_bg_urls = []
      this.remove_bg_product_id = id
      this.removeBgVisible = true
    },
    handleRemoveAllImageBg() {
      this.remove_bg_urls = []
      this.remove_bg_urls.push(this.currentOpRow.image)
      for (let i = 0; i < this.currentOpRow.image_list.length; i++) {
        this.remove_bg_urls.push(this.currentOpRow.image_list[i].url)
      }
      for (let i = 0; i < this.currentOpRow.attributes.length; i++) {
        for (let j = 0; j < this.currentOpRow.attributes[i].values.length; j++) {
          if (this.currentOpRow.attributes[i].values[j].src) {
            this.remove_bg_urls.push(this.currentOpRow.attributes[i].values[j].src)
          }
        }
      }
      this.remove_bg_product_id = this.currentOpRow.local_id
      this.removeBgVisible = true
      this.remove_bg_sync = false
    },
    handleMultiRemoveBgImageList() {
      this.remove_bg_product_id = this.currentOpRow.local_id
      this.removeBgVisible = true
      this.remove_bg_sync = false
    },
    handleUpdateImageRemoveWating(removebg) {
      for (let i = 0; i < this.currentOpRow.image_list.length; i++) {
        if (this.currentOpRow.image_list[i].url.indexOf(removebg['url']) !== -1) {
          if (removebg['removed_url']) {
            this.currentOpRow.image_list[i].restored = removebg['url'] === this.currentOpRow.image_list[i].url
            this.currentOpRow.image_list[i].url = removebg['removed_url']
          } else {
            this.currentOpRow.image_list[i].waiting_remove_bg = true
          }
        }
      }
      for (let i = 0; i < this.currentOpRow.attributes.length; i++) {
        for (let j = 0; j < this.currentOpRow.attributes[i].values.length; j++) {
          if (this.currentOpRow.attributes[i].values[j].src && this.currentOpRow.attributes[i].values[j].src.indexOf(removebg['url']) !== -1) {
            if (removebg['removed_url']) {
              this.currentOpRow.attributes[i].values[j].restored = removebg['url'] === this.currentOpRow.attributes[i].values[j].src
              this.currentOpRow.attributes[i].values[j].src = removebg['removed_url']
            } else {
              this.currentOpRow.attributes[i].values[j].waiting_remove_bg = true
            }
          }
        }
      }
    },
    // handleAddRemoveBg() {
    //   this.removeBgProcessing = true
    //   Addremovebgimage(this.removeBgForm).then(response => {
    //     this.$message.success('添加成功，等待队列处理')
    //     if (this.removeBgForm.url.length) {
    //       this.handleUpdateImageRemoveWating(this.removeBgForm.url)
    //     }
    //     if (this.remove_bg_urls.length) {
    //       for (let i = 0; i < this.remove_bg_urls; i++) {
    //         this.handleUpdateImageRemoveWating(this.remove_bg_urls[i])
    //       }
    //     }
    //     this.remove_bg_urls = []
    //     this.selected_image_list = []
    //     this.removeBgVisible = false
    //     this.removeBgProcessing = false
    //   }).catch(err => {
    //     this.this.$message.success('添加失败:' + err)
    //     this.removeBgProcessing = false
    //     this.removeBgVisible = false
    //   });
    // },
    handleRemoveImage(row) {
      this.currentOpRow.image_list = this.currentOpRow.image_list.filter(function(value, index, arr) {
        return value.url !== row.url
      })
    },
    handleModifyImageUrl(row) {
      this.$prompt('请输入图片链接', '原图链接:' + row.url, {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        row.new_url = value
        this.handleUpdateImageRemoveWating({ url: row.url, 'removed_url': value })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    handleStatusChange(row) {
      if (this.ps_product_id === '') {
        this.currentOpRow.image_list.forEach(item => {
          if (item.url !== row.url) {
            item.main = !row.main
          }
        })
        this.$notify({
          title: '成功',
          message: '',
          type: 'success',
          duration: 2000
        })
      } else {
        this.currentOpRow.image_list.forEach(item => {
          if (item.id_image !== row.id_image) {
            item.main = !row.main
          }
        })
      }
    },
    handleUpdateDirectupload() {
      this.update_direct_remote_loading = true
      crawl_update_directly_upload_remote(JSON.stringify({
        useModifyPrice: this.useModifyPrice,
        id_task: this.upload_task_id
      }))
        .then(response => {
          this.$notify({
            title: '修改成功',
            message: '',
            type: 'success',
            duration: 2000
          })
          this.update_direct_remote_loading = false
        }).catch(err => {
          this.$notify({
            title: '失败',
            message: err,
            type: 'success',
            duration: 2000
          })
          this.update_direct_remote_loading = false
        })
    },
    handleDeleteAttributeNameAllOther(mother, row) {
      this.$confirm('真的删除属性:' + row.value + '与该属性的所有组合都会删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 先删除属性组合
        this.currentOpRow.attrs_price = this.currentOpRow.attrs_price.filter((item, index, arr) => {
          let exist = false
          item.skuPropIds.split(',').forEach(item => {
            if (item === row['core-sku']) {
              exist = true
            }
          })
          return exist
        })
        mother.values = mother.values.filter((item, index, arr) => {
          return item['core-sku'] === row['core-sku']
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleDeleteAttributeName(mother, row) {
      this.$confirm('真的删除属性:' + row.value + '与该属性的所有组合都会删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 先删除属性组合
        this.currentOpRow.attrs_price = this.currentOpRow.attrs_price.filter((item, index, arr) => {
          const skus = item.skuPropIds.split(',')
          for (let i = 0; i < skus.length; i++) {
            if (skus[i] === row['core-sku']) {
              console.log('match delete')
              return false
            }
          }
          return true
          // return item.skuPropIds.indexOf(row['core-sku']) !== -1
        })
        mother.values = mother.values.filter((item, index, arr) => {
          return item['core-sku'] !== row['core-sku']
        })
        console.log('after delete mothe:', mother)
        if (mother.values.length === 0) {
          this.currentOpRow.attributes = this.currentOpRow.attributes.filter((item, index, arr) => {
            return item['name']['value'] !== mother.name.value
          })
        }
        this.$message.success('属性组合新属性添加/删除成功，组合已经重新组合。')
        this.handleReBuildAttrsPrice()
        // for (let i = 0; i < this.currentOpRow.attrs_price.length; i++) {
        //   if (this.currentOpRow.attrs_price[i].skuPropIds.indexOf(row['core-sku']) !== -1) {
        //     console.log('delete:', row.value)
        //     delete this.currentOpRow.attrs_price[i]
        //   }
        // }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleDeleteAttribute(row) {
      this.$confirm('真的删除变体组合' + row.name + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        DeleteAttribute({
          id_product: parseInt(this.ps_product_id),
          id_product_attribute: row.id_product_attribute,
          website_id: parseInt(this.currentOpRow.website_id)
        })
          .then(response => {
            this.$notify({
              title: '修复成功,请到网站检查',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            // 移除
            this.currentOpRow.ps_attributes = this.currentOpRow.ps_attributes.filter(function(item) {
              return item.id_product_attribute !== row.id_product_attribute
            })
            this.loading = false
          }).catch(err => {
            this.$notify({
              title: '失败',
              message: err,
              type: 'success',
              duration: 2000
            })
            this.loading = false
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleFixAttributes() {
      this.$confirm('此操作会增加已存在的所有变体组合,将不可恢复, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        FixAttributes({
          id_product: parseInt(this.ps_product_id),
          website_id: parseInt(this.currentOpRow.website_id)
        })
          .then(response => {
            this.$notify({
              title: '修复成功,请到网站检查',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            this.loading = false
          }).catch(err => {
            this.$notify({
              title: '失败',
              message: err,
              type: 'success',
              duration: 2000
            })
            this.loading = false
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSaveModifyLocal() {
      this.loading = true
      this.currentOpRow.modify_finsihed = this.modify_finsihed
      crawl_modify_local(JSON.stringify({
        data: this.currentOpRow,
        domain: this.domain
      }))
        .then(response => {
          this.modify_saved = true
          this.$message.success('修改成功')
          this.loading = false
        }).catch(err => {
          this.$notify({
            title: '失败',
            message: err,
            type: 'success',
            duration: 2000
          })
          this.loading = false
        })
    },
    handleSaveAsNewAndUpload(isRemote) {
      if (this.selected_website === '') {
        this.$notify({
          title: '必须选择网站',
          type: 'warning',
          duration: 5000
        })
        return
      }
      if (this.original_name === this.currentOpRow.name) {
        this.$notify({
          title: '标题未作任何修改，不允许复制,请至少修改标题，meta_description,和首图',
          type: 'warning'
        })
        return
      }
      this.loading = true
      crawl_save_as_new(JSON.stringify({
        data: this.currentOpRow,
        website_id: this.selected_website
      }))
        .then(response => {
          this.$notify({
            title: '成功',
            message: response.msg,
            type: 'success',
            duration: 2000
          })
          this.loading = false
        }).catch(err => {
          this.$notify({
            title: '失败',
            message: err,
            type: 'success',
            duration: 2000
          })
          this.loading = false
        })
    },
    handleSaveAsNewProduct(isRemote) {
      this.loading = true
      crawl_save_as_new(JSON.stringify({
        data: this.currentOpRow
      }))
        .then(response => {
          this.$notify({
            title: '成功',
            message: response.msg,
            type: 'success',
            duration: 2000
          })
          this.loading = false
        }).catch(err => {
          this.$notify({
            title: '失败',
            message: err,
            type: 'success',
            duration: 2000
          })
          this.loading = false
        })
    },
    handleModifyLocalProduct() {
      this.ps_product_id = ''
      this.local_id = this.currentOpRow.local_id
      this.url = this.currentOpRow.url
      this.showinfo = 'display:none;'
    },
    handleChangeDescription() {
      if (this.currentOpRow.long_description !== this.currentOpRow.long_description_original) {
        this.modified = true
      }
      if (this.currentOpRow.long_description === '') {
        this.modified = false
      }
    },
    handleAIRewriteTitle(row) {
      const prompt = 'rewrite product title of "' + row.name + '"'
      this.ailoading = true
      OpenAiPost({ prompt: prompt })
        .then(response => {
          row.name_old = row.name
          row.name = response.content
          this.ailoading = false
          this.$message.success(row.name_modify)
        }).catch(e => {
          console.log('error', e)
          this.ailoading = false
        })
    },
    handleAIRewritePromote(row) {
      const prompt = `Write a product promote description of "${row.name}"`
      this.aipromote_loading = true
      OpenAiPost({ prompt: prompt })
        .then(response => {
          let content = ''
          const subhs = response.content.split('.')
          for (let i = 0; i < subhs.length; i++) {
            if (subhs[i] && subhs[i].length) {
              content += '<h3>' + subhs[i] + '.</h3>'
            }
          }
          row.long_description = content + row.long_description
          this.$refs.mteditdlongdescription.setContent(row.long_description)
          this.aipromote_loading = false
          this.$message.success('获取成功')
        }).catch(e => {
          console.log('error', e)
          this.aipromote_loading = false
        })
    },
    handleModifyTabClick() {
      console.log('change tabe clean datas')
      this.$refs.imageTable.clearSelection()
      this.remove_bg_urls = []
    },
    handleSearch() {
      if (this.local_id === '') {
        return
      }
      this.resetCurrentRow()
      this.showinfo = 'display:none;'
      this.getloading = true
      this.modified = false
      this.modify_saved = false
      GetPsProduct({
        'domain': this.domain,
        'ps_product_id': this.ps_product_id,
        'local_id': this.local_id,
        'url': this.url
      }).then(respone => {
        this.currentOpRow = respone.data
        this.currentOpRow.modify_finsihed = true
        this.original_name = this.currentOpRow.name
        this.currentOpRow.long_description_original = this.currentOpRow.long_description
        if (typeof (this.ps_product_id) !== 'number' && this.ps_product_id !== '') {
          this.ps_product_id = this.currentOpRow.ps_product
        }
        this.clean_cache_url = respone.clean_cache_url
        this.getloading = false
        this.showinfo = 'display:inline;'
        this.$nextTick(() => {
          if (this.$refs.mteditdescription.hasInit && this.currentOpRow.description != null) {
            this.$refs.mteditdescription.setContent(this.currentOpRow.description != null ? this.currentOpRow.description : '')
          }
          if (this.$refs.mteditdlongdescription.hasInit) {
            this.$refs.mteditdlongdescription.setContent(this.currentOpRow.long_description != null ? this.currentOpRow.long_description : '')
          }
        })
      }).catch(e => {
        this.getloading = false
      })
    },
    close() {
      // this.ps_product_id = ''
      // this.local_id = ''
      // this.showinfo = "display:none;"
      this.currentOpRow.modified = this.modify_saved
      this.$emit('closePstDialog', this.currentOpRow)
    }
  }
}
</script>

<style scoped>

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.input-with-select {
  width: calc(100% - 200px);
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 5px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin: 10px auto !important;
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 0px;
  padding-top: 5px;
}

.top >>> .el-select {
  width: 300px;
}
</style>
